package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DeadlockLoserDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    /**
     * 菜品新增
     * @param dishDTO
     */
    @Transactional//开启事务（涉及到多张表的增删改操作）
    @Override
    public void insertDish(DishDTO dishDTO) {
        //属性拷贝
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //调用mapper保存方法
        dishMapper.insertDish(dish);
        log.info("dishId：{}", dish.getId());

        //构造菜品口味列表，将其存入dish_flavor表中
        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        //关联菜品id
        if (dishFlavors != null && dishFlavors.size() > 0){
            dishFlavors.forEach(flavor -> {
                flavor.setDishId(dish.getId());
            });
        }

        //调用mapper方法批量插入
        dishFlavorMapper.insertBatch(dishFlavors);

    }

    /**
     * 菜品分页
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageDish(DishPageQueryDTO dishPageQueryDTO) {
        //设置分页参数
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        //调用mapper并强转
        Page<DishVO> page = dishMapper.pageDish(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }
/*
* 业务规则：
* - 可以一次删除一个菜品，也可以批量删除菜品
- 起售中的菜品不能删除
- 被套餐关联的菜品不能删除
- 删除菜品后，关联的口味数据也需要删除掉
*
* */
    @Transactional//开启事务
    @Override
    public void deleteDish(List<Long> ids) {
        //1.删除菜品之前，需要进行判断菜品是否可以删除起售中的不能删除循环判断
        ids.forEach(id->{
            Dish dish = dishMapper.selectById(id);
            if (dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });
        //2.判断是否被套餐关联了，如果被套餐关联了，不能删除
        ids.forEach(id->{
            Long count = setmealDishMapper.countByDishId(id);
            if (count > 0){
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        });
//-----------------------两种不同的做法一个是直接拿到ids，一个是拿到id集合循环遍历
        //3.删除菜品基本信息dish表批量删除

        dishMapper.deleteBatch(ids);
        //4.删除菜品口味dish_flavor表
        dishFlavorMapper.deleteBatch(ids);

    }

    @Override
    public DishVO getById(Long id) {
        DishVO dishVO = new DishVO();
        //1.查询菜品id查询菜品基本信息
        Dish dish = dishMapper.selectById(id);
        //属性拷贝
        BeanUtils.copyProperties(dish,dishVO);
        //2.根据id查询口味列表数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectByDishId(id);
        //3.构造DishVo对象并返回
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }
    @Transactional//开启事务
    @Override
    public void updateDish(DishDTO dishDTO) {
        //1.修改菜品基本信息dish
        Dish dish = new Dish();
        //属性拷贝
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);
        //2.修改菜品口味列表信息dish_flavor由于要做增删改操作为了简单可以先全部删除后添加
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        //重新添加菜品口味dish_flavor数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors!=null && flavors.size()>0){
            flavors.forEach(flavor->{
                flavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }


    }

    @Override
    public void startOrStop(Integer status, Long id) {
        //构造修改对象更新菜品状态
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getByCategoryId(Long categoryId) {
        return dishMapper.getByCategoryId(categoryId);

    }
    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */

    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }


}
